import React, { useCallback, useEffect, useRef, useState } from "react";
import "./index.less";
import CommonCpasTableSS from "./CommonCpasTableSS";
import { history, useModel } from "umi";
import AntTabs from '~/public/cpas-ui/components-ui/ant-components/AntTab';
import { clearDynamicByMainTable, getSeekAuditReportTemplate, getfindDesignTableName, getjudgmentInit, gettableIsVerifyList, templateInitApi } from "./service";
import { DevPopup } from '~/public/cpas-ui';
import notify from "devextreme/ui/notify";
import { WarningOutlined } from "@ant-design/icons";
import PageLoading from "../components/PageLoading";

const TrialBalance = (props: any) => {
    const { initialState } = useModel('@@initialState');
    const { dbname, sjnd, bsdw } = initialState?.curPart as API.CurPart;
    const [valIndex, setValIndex] = useState<string>('1');
    const [spinLoad, setSpinLoad] = useState<boolean>(false);
    const [spinAntTabs, setSpinAntTabs] = useState<boolean>(true);
    const { pathname, query }: any = window.location || {};

    const [isInitBtn, setIsInitBtn] = useState<boolean>(false);
    const [loadingContent, setLoadingContent] = useState<string>('');
    const [radioVal, setRadioVal] = useState<number>(1);


    let tableNameGroup = ['试算平衡-资产表_期末', '试算平衡-资产表_期初',
        '试算平衡-负债表_期末', '试算平衡-负债表_期初',
        '试算平衡-利润表_本期', '试算平衡-利润表_上期',
        '试算平衡-现金流量表_本期', '试算平衡-现金流量表_上期',
        '试算平衡-现金补充资料表_本期', '试算平衡-现金补充资料表_上期',
        '试算平衡-所有者权益变动表_本年', '试算平衡-所有者权益变动表_上年', '试算平衡-资产减值准备情况表'
    ];

    const [excelParams, setExcelParams] = useState<any>([
        {
            cpastableParam: {
                tname: "试算平衡-资产表_期末",
                tempTname: "试算平衡-资产表_期末",
                data_id: "",
                type: "fs",
            },
            excelSheetName: "资产负债表-期末",
            tableTitle: "资产负债表",
            tableDate: " ",
            tableLfDesc: `编制单位： ${bsdw}`,
            tableRiDesc: "单位：人民币元",
            isExportTableTitle: true,
            isBatchExport: true

        },
        {
            cpastableParam: {
                tname: "试算平衡-资产表_期初",
                tempTname: "试算平衡-资产表_期初",
                data_id: "",
                type: "fs",
            },
            excelSheetName: "资产负债表-期初",
            tableTitle: "资产负债表",
            tableDate: " ",
            tableLfDesc: `编制单位： ${bsdw}`,
            tableRiDesc: "单位：人民币元",
            isExportTableTitle: true,
            isBatchExport: true

        },
        {
            cpastableParam: {
                tname: "试算平衡-负债表_期末",
                tempTname: "试算平衡-负债表_期末",
                data_id: "",
                type: "fs",
            },
            excelSheetName: "负债表-期末",
            tableTitle: "资产负债表（续）",
            tableDate: " ",
            tableLfDesc: `编制单位： ${bsdw}`,
            tableRiDesc: "单位：人民币元",
            isExportTableTitle: true,
            isBatchExport: true

        },
        {
            cpastableParam: {
                tname: "试算平衡-负债表_期初",
                tempTname: "试算平衡-负债表_期初",
                data_id: "",
                type: "fs",
            },
            excelSheetName: "负债表-期初",
            tableTitle: "资产负债表（续）",
            tableDate: " ",
            tableLfDesc: `编制单位： ${bsdw}`,
            tableRiDesc: "单位：人民币元",
            isExportTableTitle: true,
            isBatchExport: true

        },
        {
            cpastableParam: {
                tname: "试算平衡-利润表_本期",
                tempTname: "试算平衡-利润表_本期",
                data_id: "",
                type: "fs",
            },
            excelSheetName: "利润表-本期",
            tableTitle: "利润表",
            tableDate: " ",
            tableLfDesc: `编制单位： ${bsdw}`,
            tableRiDesc: "单位：人民币元",
            isExportTableTitle: true,
            isBatchExport: true

        },
        {
            cpastableParam: {
                tname: "试算平衡-利润表_上期",
                tempTname: "试算平衡-利润表_上期",
                data_id: "",
                type: "fs",
            },
            excelSheetName: "利润表-上期",
            tableTitle: "利润表",
            tableDate: " ",
            tableLfDesc: `编制单位： ${bsdw}`,
            tableRiDesc: "单位：人民币元",
            isExportTableTitle: true,
            isBatchExport: true

        },
        {
            cpastableParam: {
                tname: "试算平衡-现金流量表_本期",
                tempTname: "试算平衡-现金流量表_本期",
                data_id: "",
                type: "fs",
            },
            excelSheetName: "现金流量表-本期",
            tableTitle: "现金流量表",
            tableDate: " ",
            tableLfDesc: `编制单位： ${bsdw}`,
            tableRiDesc: "单位：人民币元",
            isExportTableTitle: true,
            isBatchExport: true

        },
        {
            cpastableParam: {
                tname: "试算平衡-现金流量表_上期",
                tempTname: "试算平衡-现金流量表_上期",
                data_id: "",
                type: "fs",
            },
            excelSheetName: "现金流量表-上期",
            tableTitle: "现金流量表",
            tableDate: " ",
            tableLfDesc: `编制单位： ${bsdw}`,
            tableRiDesc: "单位：人民币元",
            isExportTableTitle: true,
            isBatchExport: true

        },
        {
            cpastableParam: {
                tname: "试算平衡-现金补充资料表_本期",
                tempTname: "试算平衡-现金补充资料表_本期",
                data_id: "",
                type: "fs",
            },
            excelSheetName: "现金流量表补充资料-本期",
            tableTitle: "现金流量表补充资料",
            tableDate: " ",
            tableLfDesc: `编制单位： ${bsdw}`,
            tableRiDesc: "单位：人民币元",
            isExportTableTitle: true,
            isBatchExport: false

        },
        {
            cpastableParam: {
                tname: "试算平衡-现金补充资料表_上期",
                tempTname: "试算平衡-现金补充资料表_上期",
                data_id: "",
                type: "fs",
            },
            excelSheetName: "现金流量表补充资料-上期",
            tableTitle: "现金流量表补充资料",
            tableDate: " ",
            tableLfDesc: `编制单位： ${bsdw}`,
            tableRiDesc: "单位：人民币元",
            isExportTableTitle: true,
            isBatchExport: false

        },
        {
            cpastableParam: {
                tname: "试算平衡-所有者权益变动表_本年",
                tempTname: "试算平衡-所有者权益变动表_本年",
                data_id: "",
                type: "fs",
            },
            excelSheetName: "所有者权益变动表-本年",
            tableTitle: "所有者权益变动表-本年",
            tableDate: " ",
            tableLfDesc: `编制单位： ${bsdw}`,
            tableRiDesc: "单位：人民币元",
            isExportTableTitle: true,
            isColumnNum: true,
            isBatchExport: true

        },
        {
            cpastableParam: {
                tname: "试算平衡-所有者权益变动表_上年",
                tempTname: "试算平衡-所有者权益变动表_上年",
                data_id: "",
                type: "fs",
            },
            excelSheetName: "所有者权益变动表-上年",
            tableTitle: "所有者权益变动表-上年",
            tableDate: " ",
            tableLfDesc: `编制单位： ${bsdw}`,
            tableRiDesc: "单位：人民币元",
            isExportTableTitle: true,
            isColumnNum: true,
            isBatchExport: true
        },
    ]
    );


    const [antTabsData, setAntTabsData] = useState<any[]>([
        {
            tabName: '资产',
            isVerify: false,
            closable: false,
            findTableName: '试算平衡-资产表',
            tabKey: '1',
            propsData: {
                tableName: '试算平衡-资产表_期末',
                titleName: '资产负债表',
                WscwbbType: '资产类',
                templateKey: 'qmqc',
                origin: '试算平衡',
                tabsIndex: 1,
                tableRiCurrency: '人民币元'
            }
        },
        {
            tabName: '负债',
            isVerify: false,
            closable: false,
            findTableName: '试算平衡-负债表',
            tabKey: '2',
            propsData: {
                tableName: '试算平衡-负债表_期末',
                titleName: '资产负债表（续）',
                WscwbbType: '负债类',
                templateKey: 'qmqc',
                origin: '试算平衡',
                tabsIndex: 2,
                tableRiCurrency: '人民币元'
            }
        },
        {
            tabName: '利润',
            isVerify: false,
            closable: false,
            findTableName: '试算平衡-利润表',
            tabKey: '3',
            propsData: {
                tableName: '试算平衡-利润表_本期',
                titleName: '利润表',
                WscwbbType: '利润类',
                templateKey: 'bqsq',
                origin: '试算平衡',
                tabsIndex: 3,
                tableRiCurrency: '人民币元'
            }
        },
        {
            tabName: '现流',
            isVerify: false,
            closable: false,
            findTableName: '试算平衡-现金流量表',
            tabKey: '4',
            propsData: {
                tableName: '试算平衡-现金流量表_本期',
                titleName: '现金流量表',
                WscwbbType: '现金类',
                templateKey: 'bqsq',
                origin: '试算平衡',
                tabsIndex: 4,
                tableRiCurrency: '人民币元'
            }
        },
        {
            tabName: '现流附',
            isVerify: false,
            closable: false,
            findTableName: '试算平衡-现金补充资料表',
            tabKey: '5',
            propsData: {
                tableName: '试算平衡-现金补充资料表_本期',
                titleName: '现金流量表补充资料',
                WscwbbType: '现金补充资料类',
                templateKey: 'bqsq',
                origin: '试算平衡',
                tabsIndex: 5,
                tableRiCurrency: '人民币元'
            }
        },
        {
            tabName: '权益变动(本年)',
            isVerify: false,
            closable: false,
            findTableName: '试算平衡-所有者权益变动表',
            tabKey: '6',
            propsData: {
                tableName: '试算平衡-所有者权益变动表_本年',
                titleName: '所有者权益变动表',
                WscwbbType: '所有者权益变动类',
                templateKey: '',
                origin: '试算平衡',
                tabsIndex: 6,
                tableRiCurrency: '人民币元'
            }
        },
        {
            tabName: '权益变动(上年)',
            isVerify: false,
            closable: false,
            findTableName: '试算平衡-所有者权益变动表',
            tabKey: '7',
            propsData: {
                tableName: '试算平衡-所有者权益变动表_上年',
                titleName: '所有者权益变动表(续)',
                WscwbbType: '所有者权益变动类',
                templateKey: '',
                origin: '试算平衡',
                tabsIndex: 7,
                tableRiCurrency: '人民币元'
            }
        },
    ]);
    const [hideAddBtn, setHideAddBtn] = useState<boolean>(false);
    const refsCommonCpasTableSS = useRef<any>(null);
    const refsDelte = useRef<any>(1);



    const changeTabsKey = (val: string) => {
        setIsInitBtn(false);
        setValIndex(val);
        history.push('/ReportSys/trialSys/trialBalance');
    };

    const changeTabs = (changeCur: string, lxStr: string) => {
        antTabsData.forEach(item => {
            const isName = item.propsData.tableName.includes(changeCur);
            if (isName) {
                setValIndex(item.tabKey);
            }
        });
        if (lxStr) {
            const findInd = ['期末', '期初', '本期', '上期'].findIndex(itemstr => itemstr === lxStr);
            if (findInd % 2 === 0) {
                setRadioVal(1);
            } else {
                setRadioVal(2);
            }
        } else {
            setRadioVal(1);
        }
    }

    const antTabsDetail = async (dataYear: any) => {
        const res = await gettableIsVerifyList({ tableName: `${dataYear}_试算平衡`, dbname, isTid: false });
        if (res.success) {
            if (res.data?.length) {
                const tempsName = res.data.map((item: { name: string }) => item.name).join(',');
                setAntTabsData((oldData: any) => {
                    const newData = [...oldData];
                    newData.forEach((item: any) => {
                        const msg = item.findTableName;
                        const isName = tempsName.includes(msg);
                        item.isVerify = isName;
                        return item;
                    });
                    return newData;
                });
            } else {
                setAntTabsData((oldData: any) => {
                    const newData = [...oldData];
                    newData.forEach((item: any) => {
                        item.isVerify = false;
                        return item;
                    });
                    return newData;
                });
            }

            setSpinLoad(false);
        } else {
            notify(`获取isVerify校验失败！`, "error", 2000);
        }
    }
    const remove = async (targetKey: any) => {
        const auditAdjustId: any = window.localStorage.getItem(`selectDefaultSsph_${dbname}`);
        const tempYear = JSON.parse(auditAdjustId)?.ssphYearID ?? sjnd;
        await refsCommonCpasTableSS.current.clearDesignTableName(`${tempYear}_试算平衡-资产减值准备情况表`);
        setAntTabsData((item) => {
            let lastIndex: any;
            const tempData = [...item];
            tempData.forEach((pane, i) => {
                if (pane.tabKey === targetKey) {
                    lastIndex = i - 1;
                }
            });
            const newData = tempData.filter(pane => pane.tabKey !== targetKey);

            if (newData.length && valIndex === targetKey) {
                if (lastIndex >= 0) {
                    setValIndex(newData[lastIndex].tabKey);
                } else {
                    setValIndex(newData[0].tabKey);
                }
            }
            return newData;
        });

        window.localStorage.setItem(`试算平衡_资产减值准备情况表_${dbname}_${tempYear}`, JSON.stringify({
            isADD: false
        }));
        setHideAddBtn(false);
        notify(`删除资产减值标签页，成功！`, "success", 2000);

    };

    const getDesignTableName = async (funType: string) => {
        const auditAdjustId: any = window.localStorage.getItem(`selectDefaultSsph_${dbname}`);
        const tempYear = JSON.parse(auditAdjustId)?.ssphYearID ?? sjnd;
        const res = await getfindDesignTableName({ design_tableName: `${tempYear}_试算平衡-资产减值准备情况表`, dbname });
        let indexD = -1;
        indexD = antTabsData.findIndex((item) => item.propsData.tableName === `试算平衡-资产减值准备情况表`);
        if (res.success) {
            if (res.data || funType === 'addTabChange' || funType === 'addTab') {
                if (indexD < 0) {
                    setAntTabsData((item) => {
                        let newData = [...item];
                        let indexX = -1;
                        indexX = newData.findIndex((item) => item.propsData.tableName === `试算平衡-资产减值准备情况表`);
                        if (indexX < 0) {
                            newData.push({
                                tabName: '减值准备',
                                tabKey: '8',
                                isVerify: false,
                                findTableName: '试算平衡-资产减值准备情况表',
                                closable: true,
                                propsData: {
                                    tableName: '试算平衡-资产减值准备情况表',
                                    titleName: '资产减值准备情况表',
                                    WscwbbType: '资产减值准备情况类',
                                    templateKey: '',
                                    origin: '试算平衡',
                                    tabsIndex: 8,
                                    tableRiCurrency: '人民币元'
                                }
                            });
                        }
                        return newData;
                    });
                    window.localStorage.setItem(`试算平衡_资产减值准备情况表_${dbname}_${tempYear}`, JSON.stringify({
                        isADD: true
                    }));
                    if (funType === 'addTabChange') {
                        setValIndex('8');
                    }
                }

                setHideAddBtn(true);

            } else {
                if (indexD > 0) {
                    // setAntTabsData((item) => {
                    //     const tempData = [...item];
                    //     const newData = tempData.filter(pane => pane.tabKey !== '8');
                    //     return newData;
                    // });
                    // window.localStorage.setItem(`试算平衡_资产减值准备情况表_${dbname}_${tempYear}`, JSON.stringify({
                    //     isADD: false
                    // }));
                    // setHideAddBtn(false);
                    remove('8');
                }
            }
        }
    }
    const getChangeyearInitTemplate = async (isAllInit: boolean, yearTableName: string, yearData: string, actionTabs: any, tableAction: any) => {
        try {
            const judg = await getjudgmentInit({
                dbname,
                type: 'fs',
                tableRealName: yearTableName
            });
            if (judg.success) {
                if (judg.data.count_number === 0) {
                    setLoadingContent('初始化中...');
                    setSpinLoad(true);
                    const res = await getSeekAuditReportTemplate({
                        zcbfid: dbname
                    });
                    if (res.success) {
                        let tempObjs: any = {};
                        if (isAllInit) {
                            tempObjs = {
                                tableNames: tableNameGroup,
                            }
                        } else {
                            tempObjs = {
                                tableNames: ["试算平衡-资产减值准备情况表"],
                                opt: {
                                    duplicate: "cover"
                                }
                            }
                        }
                        const resTemp: any = await templateInitApi({
                            dbName: dbname,
                            templateName: res.data.AuditReportTemplate,
                            type: 'ss',
                            dataId: yearData,
                            ...tempObjs
                        });
                        setSpinLoad(false);
                        if (resTemp.success) {
                            notify(`模板初始化成功`, "success", 2000);
                            await getDesignTableName(actionTabs);
                            await clearDynamicByMainTable({
                                dbname,
                                tableRealName: yearTableName
                            });
                            if (!refsCommonCpasTableSS.current) return;
                            await refsCommonCpasTableSS.current.CPASInit(yearTableName, true);
                            await antTabsDetail(yearData);
                        } else {
                            if (tableAction === 'tableben' || tableAction === 'tableSSYear') {
                                await getDesignTableName(actionTabs);
                                if (refsCommonCpasTableSS.current) {
                                    await refsCommonCpasTableSS.current.pathnameRunFun(yearTableName, yearData);
                                }
                            }
                            if (res.data.AuditReportTemplate) {
                                notify(`${resTemp.msg}`, "error", 2000);
                            } else {
                                notify(`请在首页组成部分信息内选择报告模板`, "warning", 2000);
                            }
                        }
                    }
                } else {
                    // if (tableAction === 'tableben' || tableAction === 'tableSSYear') {}
                    await getDesignTableName(actionTabs);
                    if (!refsCommonCpasTableSS.current) return;
                    await refsCommonCpasTableSS.current.CPASInit(yearTableName, false);
                    await antTabsDetail(yearData);
                }
                setIsInitBtn(false);
            } else {
                notify(`获取判断是否初始化失败！`, "error", 2000);
            }
        } catch (error) {
            notify(`获取判断是否初始化失败！`, "error", 2000);
        }
    };
    const add = () => {
        if (!refsCommonCpasTableSS.current) return;
        setIsInitBtn(true);// 重要
        const auditAdjustId: any = window.localStorage.getItem(`selectDefaultSsph_${dbname}`);
        const tempYear = JSON.parse(auditAdjustId)?.ssphYearID ?? sjnd;
        getChangeyearInitTemplate(false, `${tempYear}_试算平衡-资产减值准备情况表`, tempYear, 'addTabChange', 'tableben');
        notify(`添加资产减值标签页，成功！`, "success", 2000);
    };

    const onEdit = (
        targetKey: React.MouseEvent | React.KeyboardEvent | string,
        action: 'add' | 'remove',
    ) => {
        if (action === 'add') {
            add();
        } else {
            refsDelte.current.show({
                title: "删除提醒",
                okCallback: () => {
                    remove(targetKey);
                }
            });

        }
    };




    const changeSpinAntTabs = async (newData: boolean, yearTableName: any) => {
        setSpinAntTabs(newData);
        setIsInitBtn(false); /* setIsInitBtn(false); 这个状态很重要; 请勿删除！ 20230727 */
        setValIndex('1');
        const auditAdjustId: any = window.localStorage.getItem(`selectDefaultSsph_${dbname}`);
        const tempYear = JSON.parse(auditAdjustId)?.ssphYearID ?? sjnd;
        if (newData && refsCommonCpasTableSS.current) {
            await getDesignTableName('');
            refsCommonCpasTableSS.current.CPASInit(`${tempYear}_试算平衡-资产表_期末`, false);
            // antTabsDetail(yearData);
        }
    }

    useEffect(() => {
        console.log('@@@ useEffectSS ');
        // const auditAdjustId: any = window.localStorage.getItem(`selectDefaultSsph_${dbname}`);
        // const tempYear = JSON.parse(auditAdjustId)?.ssphYearID ?? sjnd;
        // getDesignTableName();
    }, []);

    useEffect(() => {
        console.log(query, pathname, '@@@ query.tableName');

        if (pathname === '/ReportSys/trialSys/trialBalance' && query.tableName) {
            const tempTableName = query.tableName.split('_');
            if (tempTableName[0]) {
                let selectDefaultIDs = { ssphYearID: tempTableName[0] };
                // // 本地存储 持久化数据
                window.localStorage.setItem(`selectDefaultSsph_${dbname}`, JSON.stringify(selectDefaultIDs));
                changeTabs(tempTableName[1], tempTableName[2]);
            }
        }
    }, [pathname, query]);


    return (<div className="trialBalance_whole">
        {/* {spinLoad && <SpinLoading loadString="正在初始化 ..." />} */}
        <PageLoading
            isOpen={spinLoad}
            isMaskClose={false}
            content={loadingContent}
            width={200}
        />

        {spinAntTabs && <AntTabs defaultActiveKey="1"
            className="changeTabsHeight"
            type="editable-card"
            destroyInactiveTabPane={true}
            onChange={(val: string) => { changeTabsKey(val) }} activeKey={valIndex}
            onEdit={onEdit} hideAdd={hideAddBtn}
        >
            {
                antTabsData.map((item: any) => (
                    <AntTabs.TabPane tab={
                        <span>{item.tabName}
                            {item.isVerify && <span className="render-span"
                                onClick={() => {
                                    if (refsCommonCpasTableSS.current) {
                                        refsCommonCpasTableSS.current.CPASOpenDetail();
                                    }
                                }}>
                                <WarningOutlined />
                            </span>}
                        </span>
                    }
                        key={item.tabKey} closable={item.closable} >
                        <CommonCpasTableSS
                            isInitBtn={isInitBtn}
                            CPASTableTabName={item.tabName}
                            changeIsInitBtn={() => {
                                setIsInitBtn(false);
                            }}

                            biaoAllData={antTabsData}
                            getChangeyearInitTemplate={(isAllInit: boolean, yearTableName: string, yearData: string, tabStatus: any, tableAction: any) => getChangeyearInitTemplate(isAllInit, yearTableName, yearData, tabStatus, tableAction)}
                            CPASTableProps={item.propsData} excelParams={excelParams}
                            cpasChangeSpinAntTabs={(data: boolean, yearTableName: any) => { changeSpinAntTabs(data, yearTableName) }}
                            antTabsTabPaneDetail={(selectyYear: any) => antTabsDetail(selectyYear)} ref={refsCommonCpasTableSS} tableNameGroup={tableNameGroup}
                            radioVal={radioVal}
                        // spinUseEffect={spinUseEffect}
                        />
                    </AntTabs.TabPane>
                ))
            }

        </AntTabs>}
        <DevPopup.Default ref={refsDelte} width={80} height={220}  >
            {() => {
                return <span>确定要执行此删除操作吗？</span>
            }}
        </DevPopup.Default>
    </div>
    )
}
export default TrialBalance;
